package com.jt.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jt.mapper.UserMapper;
import com.jt.pojo.User;
import com.jt.utils.ObjectMapperUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import redis.clients.jedis.JedisCluster;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service(timeout = 3000)
public class DubboUserServiceImpl implements DubboUserService{
    @Autowired
    UserMapper userMapper;
    @Autowired
    JedisCluster jedisCluster;
    @Override
    public List<User> findAll() {
        return userMapper.findAll();
    }

    @Override
    public String doLogin(User user) {
        // 1.将明文加密
        String md5Pass = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(md5Pass);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>(user);
        // 根据对象中不为null的属性当做where条件.
        User userDB = userMapper.selectOne(queryWrapper);
        //用户名或密码错误
        if (userDB == null)
            return null;
        //用户名和密码正确  实现单点登录操作
        String ticket = UUID.randomUUID().toString();
        //如果将数据保存到第三方 一般需要脱敏处理
        userDB.setPassword("这不是密码其实");
        String userJson = ObjectMapperUtil.toJson(userDB);
        jedisCluster.setex(ticket, 7 * 24 * 60 * 60, userJson);
        return ticket;
    }

    @Override
    public void saveUser(User user) {
        String password = user.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        user.setEmail(user.getPhone()).setPassword(password);
        userMapper.insert(user);
    }

    private static Map<Integer, String> paramType = new HashMap<>();
    static {
        paramType.put(1,"username");
        paramType.put(2,"phone");
        paramType.put(3,"email");

    }
    @Override
    public boolean checkUser(String param, Integer type) {
        //1.需要将type类型转化为 具体字段信息  1=username  2=phone  3=email
        String column = paramType.get(type);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(column, param);
        Integer count = userMapper.selectCount(queryWrapper);
        return  count > 0 ? true :false;
    }


}
